# -*- coding: utf8 -*-
from __future__ import print_function

import re
import os
import sys

from subprocess import Popen, PIPE

def execute(*args,  **options):
    '''
    to run application, by default, its output will be captured and returned.
    '''
    debug_level = options.get("debug", "")
    verbose = options.get("verbose", True)
    # effective only when verbose is False
    showlog = options.get("showlog", 0)

    if len(args) < 1:
        raise Exception("Invalid call to execute()!")
    elif len(args) == 1:
        args = args[0]

    if not isinstance(args, list):
        result = []
        for ele in args.split(' '):
            if len(ele):
                result.append(ele)
        args = result

    if verbose:
        if "err" in options.get("capture", ""):
            p = Popen(args, stderr=PIPE)
        else:
            p = Popen(args)
    else:
        p = Popen(args, stdout=PIPE, stderr=PIPE)
    output, err = p.communicate()

    if "I" in debug_level or "D" in debug_level:
        print("INFO : cmd       : %s" % (str(args)))
        print("INFO : cmd result: %d" % (p.returncode))

    if not verbose and showlog > 0:
        if len(err) > 0:
            print("INFO: error output.")
            print(err)

        if len(output) > 0:
            lines = re.split(r"\r|\n", output)
            for ele in lines[-showlog:]:
                print(ele)

    try:
        output = output.decode("utf-8")
    except:
        pass

    try:
        err = err.decode("utf-8")
    except:
        pass

    return p.returncode, output, err



def get_repo_root():
    """
    get root folder for the current repository
    """
    code, root, _ = execute("git rev-parse --show-toplevel", verbose=False)
    if code != 0 or root is None:
        return None

    return root.strip()

